package com.fly.docker.web;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fly.docker.service.DockerService;
import com.fly.docker.sse.SSEServer;
import com.spotify.docker.client.exceptions.DockerException;

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Api(tags = "SSE")
@RestController
@RequestMapping("/sse")
public class SseController
{
    @Autowired
    DockerService dockerService;
    
    ObjectMapper objectMapper = new ObjectMapper();
    
    @CrossOrigin
    @GetMapping("/connect")
    public SseEmitter connect()
    {
        SseEmitter sseEmitter = SSEServer.connect();
        initData(sseEmitter);
        return sseEmitter;
    }
    
    /**
     * 提供UI初始数据
     * 
     * @param sseEmitter
     * @see [类、类#方法、类#成员]
     */
    private void initData(SseEmitter sseEmitter)
    {
        try
        {
            log.info("initData...");
            sseEmitter.send(objectMapper.writeValueAsString(dockerService.getContainers()), MediaType.APPLICATION_JSON);
        }
        catch (IOException | DockerException | InterruptedException e)
        {
            log.error(e.getMessage(), e);
        }
    }
}
